#include "Contacts.h"
#include <stdio.h>

struct Contacts
{
    ElementType *Person;
    int capacity;
    int size;
};

void UI()
{
    printf("  **1.插入新用户**  \n");
    printf("  **2.删除用户**  \n");
    printf("  **3.查看用户**  \n");
    printf("  **4.修改用户**  \n");
    printf("  **5.打印信息**  \n");
    printf("  **6.退出**  \n");
}

Conts* InitConts()
{
    Conts *a = (Conts*)malloc(sizeof(Conts));
    if(a == NULL)
    {
        printf("InitDArray malloc error\n");
        exit(-1);
    }
    a->size = 0;
    a->capacity = 10;
    a->Person = (ElementType*)malloc(sizeof(ElementType) * a->capacity);
    if(a->Person == NULL )
    {
        printf("InitConts array malloc error\n");
        exit(-1);
    }
    return a;
}

void InsertConts(Conts *a, ElementType element)
{
    if(a->size == a->capacity)
    {
        a->capacity *= 2;
        a->Person = (ElementType*)realloc(a->Person,a->capacity * sizeof(ElementType));
        if(a->Person == NULL)
        {
            printf("InsertConts realloc error\n");
            exit(-1);
        }
    }
    a->Person[a->size++] = element; 
}

void printConts(Conts *a, void (*print)(ElementType))
{
    printf("capacity: %d   size: %d\n",a->capacity,a->size);
    for(int i = 0;i < a->size;i++)
        print(a->Person[i]);
    printf("\n");
}

ElementType FindByElement(Conts *a, ElementType value, bool (*compare)(ElementType, ElementType))
{
    for(int i = 0;i < a->size;i++)
    {
        if(compare(a->Person[i],value))
            return a->Person[i];
    }
    return NULL;
}

ElementType RemoveByIndex(Conts *a,int index)
{
    ElementType result = a->Person[index];
    for(int i = index;i < a->size - 1;i++)
    {
        a->Person[i] = a->Person[i + 1];
    }
    a->size--;
    return result;
}

ElementType RemoveByElement(Conts *a, ElementType value, bool (*compare)(ElementType, ElementType))
{
    for(int i = 0;i < a->size;i++)
    {
        if(compare(a->Person[i],value))
            return RemoveByIndex(a,i);
    }
    return NULL;
}

void ClearConts(Conts *a, void (*clear)(ElementType))
{
    if(a != NULL)
    {
        for(int i = 0;i < a->size;i++)
            clear(a->Person[i]);
        free(a->Person);
        free(a);
    }
}
